<?php


namespace app\model;


use app\services\Lottery;
use think\facade\Db;
use think\Model;
use utils\Define;

class CommodityLotteryLog extends Model
{


    /**
     * 抽奖
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lottery($data)
    {
        RedisLock('Lotteryssss_' . $data->user_id);
        $address = Db::name('address')->where(['user_id' => $data->user_id, 'is_default' => 1])->find();
        if (!$address) {
            return app('json')->json_error('请设置默认地址后在进行抽奖');
        }
        Db::startTrans();
        try {
            $result = ['id' => 1, 'name' => '谢谢参与！', 'lottery_id' => '', 'num' => 0, 'goods_id' => '', 'is_lottery' => 0, 'is_five_lottery' => 0, 'image' => ''];
            switch ($data->data['type']) {
                case 1:
                    $res = app()->make(Lottery::class)->luckyGift($result);
                    switch ($res['id']) {
                        case 2:
                            //积分奖励
                            MoneyLog::SetUserMoney($data->user_id, $data->user->integral, $res['rand_integral'], 9);
                            break;
                    }
                    $res['is_five_lottery'] = 0;
                    $u_in = 5;
                    break;
                case 2:
                    $u_in = 200;
                    $res = app()->make(Lottery::class)->other($data->user_id, $result, $data->data['type']);
                    break;
                case 3:
                    $u_in = 1000;
                    $res = app()->make(Lottery::class)->other($data->user_id, $result, $data->data['type']);
                    break;
                case 4:
                    $u_in = 5000;
                    $res = app()->make(Lottery::class)->other($data->user_id, $result, $data->data['type']);
                    break;
                case 5:
                    $u_in = 12000;
                    $res = app()->make(Lottery::class)->other($data->user_id, $result, $data->data['type']);
                    break;
                default:
                    Db::rollback();
                    return app('json')->json_error('失败');
            }
            if ($data->user->integral < $u_in) {
                Db::rollback();
                return app('json')->json_error('余额不足');
            }
            //查看是否中商品
            if ($res['is_lottery'] == 1) {
                //保存订单与商品
                app()->make(CommodityOrder::class)->LotteryOrder($res['goods_id'], $data->user_id, $address['id']);
            }
            //保存抽奖日志
            $this->SetLotteryLog($data->user_id, $res['goods_id'], $res['name'], $res['lottery_id'], $data->user->phone, $data->user->avatar, $data->data['type'], $res['is_lottery'], $res['is_five_lottery'], $u_in);
            //保存流水日志
            //扣除用户积分
            $user = User::where(['id' => $data->user_id])->find();
            MoneyLog::SetUserMoney($data->user_id, $user->integral, $u_in, 8, 2);
            $user->integral -= $u_in;
            $user->save();
            Db::commit();
            unset($res['is_five_lottery']);
            $res['user_integral'] = $user->integral;
            return app('json')->json_success('成功', $res);
        } catch (\Exception $exception) {
            Db::rollback();
            return app('json')->json_error('失败' . $exception->getMessage());
        }
    }


    /**
     * 抽奖日志
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function LotteryLog($data)
    {
        $result = Db::name('commodity_lottery_log')
            ->field('id,type,user_id,is_lottery,created_time,integral,goods_name as lottery_intro')
            ->withAttr('type', function ($value, $data) {
                return $this->type($value);
            })
            ->withAttr('created_time', function ($value, $data) {
                return date('Y-m-d', strtotime($value));
            })
            ->where(['user_id' => $data->user_id])
            ->paginate($data->data['limit'])
            ->toArray();
        return app('json')->json_success('成功', $result);
    }


    /**
     * 中奖日志
     * @param $data
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function WinnerLog($data)
    {
        $result = Db::name('commodity_lottery_log')
            ->where('is_lottery', '<>', 0)
            ->field('id,goods_name,phone,avatar')
            ->withAttr('phone', function ($value, $data) {
                return mb_substr($value, 0, 4) . '****' . mb_substr($value, -3);
            })
            ->paginate($data->data['limit'])
            ->toArray();
        return app('json')->json_success('成功', $result);
    }


    /**
     * 类型
     * @param $type
     * @return string
     */
    public static function type($type)
    {
        $type = Define::LotteryType[$type] ?: '';
        return $type;
    }


    /**
     * 保存中奖日志
     * @param $user_id
     * @param $goods_id
     * @param $goods_name
     * @param $lottery_id
     * @param $phone
     * @param $type
     * @param int $is_lottery
     * @param int $is_five_lottery
     */
    public function SetLotteryLog($user_id, $goods_id, $goods_name, $lottery_id, $phone, $avatar, $type, $is_lottery = 0, $is_five_lottery = 0, $integral)
    {
        $lottery_save = array(
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'goods_name' => $goods_name,
            'lottery_id' => $lottery_id,
            'phone' => $phone,
            'type' => $type,
            'is_lottery' => $is_lottery,
            'is_five_lottery' => $is_five_lottery,
            'integral' => $integral
        );
        $this->save($lottery_save);
    }


    /**
     * 抽奖前置信息
     * @param $data
     * @return mixed
     */
    public function LotteryMsg($data)
    {
        //剩余次数
        $arr['remaining_num'] = 0;
        $arr['total_num'] = 0;
        switch ($data->data['type']) {
            case  1:
                //消耗积分
                $arr['consume_points'] = SystemConfig('lucky_gift') ?: 0;
                break;
            case 2:
                $lottery_log_count = self::where(['user_id' => $data->user_id, 'type' => 2])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->count();
                $arr['remaining_num'] = 6-$lottery_log_count;
                $arr['consume_points'] = 200;
                $arr['total_num'] = 6;
                break;
            case 3:
                $lottery_log_count = self::where(['user_id' => $data->user_id, 'type' => 3])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->count();
                $arr['remaining_num'] = 6-$lottery_log_count;
                $arr['consume_points'] = 1000;
                $arr['total_num'] = 6;
                break;
            case 4:
                $lottery_log_count = self::where(['user_id' => $data->user_id, 'type' => 4])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->count();
                $arr['remaining_num'] = 6-$lottery_log_count;
                $arr['consume_points'] = 5000;
                $arr['total_num'] = 6;
                break;
            case 5:
                $lottery_log_count = self::where(['user_id' => $data->user_id, 'type' => 5])->whereTime('created_time', 'between', [DateTime()['t_s'], DateTime()['t_e']])->count();
                $arr['remaining_num'] = 6-$lottery_log_count;
                $arr['consume_points'] = 12000;
                $arr['total_num'] = 6;
                break;
        }
        return app('json')->json_success('成功', $arr);
    }

}